package com.ymk.base.utlis;

import com.google.gson.JsonSyntaxException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.util.Date;

/**
 * @author: zkl
 * @description: gson解析date类型空字符串
 * @create: 2019-07-03 10:18
 **/

public class DateTypeAdapter extends TypeAdapter<Date> {
    @Override
    public void write(JsonWriter out, Date value) throws IOException {
        out.value(String.valueOf(value));
    }

    @Override
    public Date read(JsonReader in) throws IOException {
        if (in.peek() == JsonToken.NULL) {
            in.nextNull();
            return null;
        }
        try {
            String result = in.nextString();
            if ("".equals(result)) {
                return null;
            }
            String formatStr = result.length() == 10 ? "yyyy-MM-dd" : "yyyy-MM-dd HH:mm:ss";
            if (result.indexOf('Z') > 0) {
                result = result.replace("Z", " UTC");
                formatStr = "yyyy-MM-dd'T'HH:mm:ss.SSS Z";
            }
            return DateUtil.stringToDate(result, formatStr);
        } catch (NumberFormatException e) {
            throw new JsonSyntaxException(e);
        }
    }
}
